package code.class2;

import java.util.Arrays;

/**
 * https://leetcode.cn/problems/split-array-largest-sum/description/
 * (分割数组最大值)画匠问题
 */
public class Code02_Drawer {
    public static void main(String[] args) {
        int[] nums = {7, 2, 5, 10, 8};
        int k = 2;
        int i = splitArray(nums, k);
        System.out.println("i = " + i);
    }

    public static int splitArray(int[] nums, int k) {
        int l = 0, mid, r = Arrays.stream(nums).sum();
        int ans = 0;
        while (l <= r) {
            mid = l + ((r - l) >> 1);
            int cur = f(nums, mid); // 当前值是否能取前
            if (cur <= k) {
                ans = mid;
                r = mid - 1;
            } else {
                l = mid + 1;
            }
        }
        return ans;
    }

    /**
     * f函数处理判断范围
     * aim为桶的大小
     */
    private static int f(int[] nums, int aim) {
        int p = 1;
        int sum = 0; // 计算每部分的累加和
        for (int num : nums) {
            if (num > aim) {
                return Integer.MAX_VALUE;
            }
            // 当桶的累加和>aim的容积，切到下一个桶，并将num设置为sum的初始值
            if (sum + num > aim) {
                p++;
                sum = num;
            } else { // 当累加和<aim容积，则继续累加
                sum += num;
            }
        }
        return p;// 返回通的大小
    }

}
